﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
using System.Security.Policy;
using System.Web.Mvc;
using System.Configuration;
using log4net;

namespace PersonalWebSite.Common
{
    /// <summary>
    /// Defines the wallpaper helper class
    /// </summary>
    public class Wallpaper
    {
        #region Variables
        private const string cacheKeyWallpaperList = "WallpaperList";
        private const string sessionKeyRemainingWallpaperList = "WallpaperRemainingList";
        private const string sessionKeyCurrentWallpaperPath = "WallpaperCurrentWallpaperPath";
        private static readonly string wallpapersBasePath = "~/Content/img/wallpapers";
        private static readonly string[] validWallpapaerFileExtensions = new string[]{".jpg", ".jpeg", ".png", ".bmp", ".gif"};
        private static int defaultWallpaperChangeInterval = 45000;

        private static readonly ILog logger = LogManager.GetLogger(typeof(Wallpaper));
        #endregion

        #region Properties
        /// <summary>
        /// Gets all the wallpaper paths
        /// </summary>
        /// <remarks>
        /// Value is being cached
        /// </remarks>
        private static string[] WallpaperPaths
        {
            get
            {
                return Cache.CacheItem<string[]>(cacheKeyWallpaperList, () => FetchAllWallpapers());
            }
        }

        /// <summary>
        /// Gets or Sets the remaining wallpaper paths
        /// </summary>
        private static string[] RemainingWallpaperPaths
        {
            get
            {
                return HttpContext.Current.Session[sessionKeyRemainingWallpaperList] as string[];
            }
            set
            {
                HttpContext.Current.Session[sessionKeyRemainingWallpaperList] = value;
            }
        }

        /// <summary>
        /// Gets the wallpaper change interval
        /// </summary>
        public static int WallpaperChangeInterval
        {
            get
            {
                int interval;
                if (!int.TryParse(ConfigurationManager.AppSettings["WallpaperChangeInterval"], out interval))
                    interval = defaultWallpaperChangeInterval;
                return interval;
            }
        }

        /// <summary>
        /// Gets the current wallpaper image path
        /// </summary>
        public static string CurrentWallpaperImagePath
        {
            get
            {
                return HttpContext.Current.Session[sessionKeyCurrentWallpaperPath] as string;
            }
        }
        #endregion

        #region Constructor
        /// <summary>
        /// Inits the class
        /// </summary>
        static Wallpaper()
        {
            log4net.Config.XmlConfigurator.Configure();
        }
        #endregion

        /// <summary>
        /// Fethces the image path of the next wallpaper path to display
        /// </summary>
        /// <returns></returns>
        public static string FetchNextWallpaperImagesPath()
        {
            string[] remainingWallpaperList = RemainingWallpaperPaths;
            if (remainingWallpaperList == null || remainingWallpaperList.Length == 0)
                remainingWallpaperList = WallpaperPaths;

            string nextWallpaperPath = remainingWallpaperList[new Random().Next(remainingWallpaperList.Length - 1)];

            RemainingWallpaperPaths = (from i in remainingWallpaperList where i != nextWallpaperPath select i).ToArray();

            HttpContext.Current.Session[sessionKeyCurrentWallpaperPath] = nextWallpaperPath;

            return nextWallpaperPath;
        }

        #region Helper Methods
        /// <summary>
        /// Fethces all the available wallpaper image paths
        /// </summary>
        /// <returns>wallpaper image paths</returns>
        private static string[] FetchAllWallpapers()
        {
            try
            {
                string basePath = HttpContext.Current.Server.MapPath(wallpapersBasePath);
                return Directory.GetFiles(basePath, "*.*", SearchOption.AllDirectories).Where(s => validWallpapaerFileExtensions.Any(e => s.ToLower().EndsWith(e))).Select(s => wallpapersBasePath + "/" + s.Substring(s.LastIndexOfAny(new char[] { '/', '\\' }) + 1)).ToArray();
            }
            catch (Exception ex)
            {
                logger.Error("Error occured while trying to fetch all wallpapers list", ex);
                return new string[0];
            }
        }
        #endregion
    }
}